import React, {useState, useEffect} from 'react';
import {useHistory} from 'react-router-dom';
import {Map, Marker} from 'react-amap';

import {Form, Input, InputNumber, Button, Row, Col, Upload, message, Modal} from 'antd';
import {LoadingOutlined, PlusOutlined, CloseCircleOutlined} from '@ant-design/icons';
import Ckeditor from '@src/components/ckeditor/Ckeditor';
import axios from '@src/lib/axios';
import PageTitle from "@src/components/PageTitle";

const {Search} = Input;

import '@src/style/hotel.scss';

function BaseInfo({id}) {
    const history = useHistory();
    const [form] = Form.useForm();
    const [mapPlugins, setMapPlugins] = useState(['ToolBar']);
    const [mapCenter, setMapCenter] = useState({longitude: 116.407526, latitude: 39.904030});
    const [markerPosition, setMarkerPosition] = useState({longitude: 116.407526, latitude: 39.904030});
    const [tmpLongitude, setTmpLongitude] = useState("");
    const [tmpLatitude, setTmpLatitude] = useState("");


    const [loading, setLoading] = useState(false);
    let ck1 = '';
    const [uploadFileList, setUploadFileList] = useState([]);
    // const [fileList, setFileList] = useState([]);
    const [previewVisible, setPreviewVisible] = useState(false);//预览弹窗的visible
    const [previewImage, setPreviewImage] = useState('');//预览image的内容


    useEffect(() => {
        if (id) {
            axios.post('/activity/hot/product/info', {id}).then(res => {
                if (res.code === 0) {
                    let data = res.data;
                    if (data.x != 0 && data.y != 0) {
                        console.log(33333)
                        setMapCenter({
                            ...mapCenter,
                            longitude: data.x,
                            latitude: data.y
                        })
                        setMarkerPosition({
                            ...markerPosition,
                            longitude: data.x,
                            latitude: data.y
                        })
                        setTmpLongitude(data.x)
                        setTmpLatitude(data.y)
                    }
                    let {product_desc} = data;
                    ck1 && ck1.setData(product_desc);
                    let imageIds = data.image_ids

                    if (imageIds) {
                        imageIds = imageIds.split(',')
                        //setFileList(imageIds)
                        let uploadFileList = [];
                        imageIds.forEach(function (v) {
                            uploadFileList.push({
                                uid: v,
                                name: v,
                                status: "done",
                                url:  process.env.IMG_SERVER_URL+"/"+v
                            })
                        })
                        console.log(uploadFileList);
                        setUploadFileList(uploadFileList)
                    }

                    form.setFieldsValue({
                        ...data
                    })
                }
            })
        }
    }, [id]);


    let onRemove = (file) => {
        console.log('remove:', file)
    }

    //拾取商家地理位置坐标
    let geoCode = (address) => {
        axios.post('/map/geo_code', {address}).then(res => {
            if (res.code === 0) {
                let {data} = res
                setMapCenter({
                    ...mapCenter,
                    longitude: data[0],
                    latitude: data[1]
                })
                setMarkerPosition({
                    ...markerPosition,
                    longitude: data[0],
                    latitude: data[1],
                })
                setTmpLongitude(data[0])
                setTmpLatitude(data[1])

                form.setFieldsValue({x: data[0]})
                form.setFieldsValue({y: data[1]})
                message.success("ok")
            } else {
                message.warning(res.msg)
            }

        }).catch(res => {
            console.log(res)
        });
    };

    let changeCenter = () => {
        console.log(tmpLongitude,tmpLatitude);

        if (tmpLongitude &&  tmpLatitude) {
            setMapCenter({
                ...mapCenter,
                longitude: tmpLongitude,
                latitude: tmpLatitude
            })
            setMarkerPosition({
                ...markerPosition,
                longitude: tmpLongitude,
                latitude: tmpLatitude
            })
        }
    };

    //经度
    let xOnchange = (value) => {
        let v = value.target.value;
        v && setTmpLongitude(v)

    }
    //纬度
    let yOnchange = (value) => {
        let v = value.target.value
        v && setTmpLatitude(v)
    }


    let onFinish = (value) => {
        console.log(uploadFileList)
        let imageIds = [];
        uploadFileList.map(function (item) {
            if (item.url !== undefined) {
                imageIds.push(item.name)
            } else if (item.status === 'done') {
                if (item.response.code === 200) {
                    imageIds.push(item.response.data.imgid)
                }
            } else {
                console.log(item)
            }
        })
        if (imageIds) {
            imageIds = imageIds.join(',');
        } else {
            imageIds = "";
        }
        let data = form.getFieldsValue();
        Object.assign(data, {image_ids: imageIds, id: id});

        axios.post("/activity/hot/product/update", data).then(res => {
            message.success(res.msg);
            history.push('/activity/package');
        }).catch(res => {
            console.log(res)
        });
    }

    let handleChange = (info) => {

        let file = info.file;
        let fileList = [...info.fileList];
        console.log(fileList)
        setUploadFileList([...fileList]);
    }

    let ckChangeHandler = (k, instan) => {
        form.setFieldsValue({[k]: instan.getData()});
    };

    let ckReadyHandler = (instan, vk) => {
        instan.setData(form.getFieldValue(vk));
    };
    let handPreview = async file => {
        setPreviewImage(file.url || file.thumbUrl);
        setPreviewVisible(true);
    };


    const handleCancel = () => setPreviewVisible(false);


    const uploadProps = {
        name: "userfile",
        action: "/images_serv/",
        listType: "picture-card",
        onRemove: onRemove,
        onChange: handleChange,
        fileList: uploadFileList,
        onPreview: handPreview
    }
    const uploadBtn = (
        <div>
            <PlusOutlined/>上传
        </div>
    )

    return (
        <div className="container" style={{position: 'relative'}}>
            <PageTitle title='编辑产品' showBack/>
            <Form
                form={form}
                name={"activity_product"}
                onFinish={onFinish}
                labelCol={{span: 2}}
                wrapperCol={{span: 20}}
            >
                <Row className="fields-box">
                    <Col span={24}>
                        <Form.Item
                            label="产品名称"
                            name="product_name"
                            rules={[{required: true, message: '请输入产品名称!'}]}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="商家电话"
                            name={"merchants_phone"}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label="产品图片">
                            <Upload {...uploadProps}>
                                {uploadFileList.length > 5 ? null : uploadBtn}
                            </Upload>
                        </Form.Item>
                        <Form.Item
                            label="产品描述"
                            name="product_desc"
                            rules={[
                                {required: true, message: '产品描述必须填写！'}
                            ]}
                        >
                            <Ckeditor editorId="kids" readyHandler={(instan) => {
                                ck1 = instan;
                                ckReadyHandler(instan, 'product_desc')
                            }} changeHandler={(instan) => ckChangeHandler('product_desc', instan)}></Ckeditor>
                        </Form.Item>
                        <Row>
                            <Col span={6} style={{paddingLeft: 45}}>
                                <Form.Item
                                    labelCol={1}
                                    label="库存"
                                    name="stock"
                                    rules={[
                                        {required: true, message: "库存必须填写"}
                                    ]}
                                >
                                    <InputNumber/>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item
                                    labelCol={1}
                                    label="平台价"
                                    name="platform_price"
                                    rules={[
                                        {required: true, message: "平台价必须填写"}
                                    ]}
                                >
                                    <InputNumber min={1} max={999}/>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item
                                    labelCol={1}
                                    label="结算价"
                                    name="settlement_price"
                                    rules={[
                                        {required: true, message: "结算价必须填写"}
                                    ]}
                                >
                                    <InputNumber min={1} max={999}/>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item
                                    labelCol={1}
                                    label="市场价"
                                    name={"market_price"}
                                    rules={[
                                        {required: true, message: "市场价必须填写"}
                                    ]}
                                >
                                    <InputNumber/>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={6}>
                                <Form.Item
                                    labelCol={1}
                                    label="分销商返佣"
                                    name="rebate_m_percent"
                                    rules={[
                                        {required: true, message: "不能为空"}
                                    ]}
                                >
                                    <InputNumber min={1} max={999}/>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item
                                    labelCol={1}
                                    label="普通用户返佣"
                                    name={"rebate_c_percent"}
                                    rules={[
                                        {required: true, message: "不能为空"}
                                    ]}
                                >
                                    <InputNumber min={1} max={999}/>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item
                                    labelCol={1}
                                    label="最低成团数"
                                    name={"spell_limits"}
                                    rules={[
                                        {required: true, message: "不能为空"}
                                    ]}
                                >
                                    <InputNumber min={1} max={999}/>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item
                                    labelCol={1}
                                    label="虚拟成功拼团数"
                                    name={"virtual_limits"}
                                >
                                    <InputNumber/>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Form.Item
                            label={"产品标签"}
                            name={"tag"}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label={"排序值"}
                            name={"sort_value"}
                        >
                            <InputNumber/>
                        </Form.Item>
                        <Form.Item
                            label={"商家名称"}
                            name={"merchants_name"}
                        >
                            <Input/>
                        </Form.Item>
                        <Form.Item
                            label={"商家地址"}
                            name={"merchants_address"}
                        >
                            <Search
                                placeholder="输入商家地址：省+市+区+县+街道+门牌号"
                                onSearch={value => geoCode(value)}
                                enterButton="拾取商家地理坐标"
                                style={{width: 500}}
                            />
                        </Form.Item>
                        <Form.Item
                            label={"经度"}
                            name={"x"}
                        >
                            <Input onChange={value => xOnchange(value)} style={{width: "20%"}}/>
                        </Form.Item>
                        <Form.Item
                            label={"纬度"}
                            name={"y"}
                        >
                            <Input onChange={value => yOnchange(value)} style={{width: "20%"}}/>
                        </Form.Item>
                        <Row>
                            <Col>
                                <Button type="link" href={"https://lbs.amap.com/console/show/picker"}
                                        target={"_blank"}>去高德地图坐标拾取器获取经纬度</Button>
                                <Button size={"small"} type="primary" name={"2332"}
                                        onClick={() => changeCenter()}>点我查看定位</Button>
                            </Col>
                        </Row>
                    </Col>

                </Row>
                <Form.Item label="所在位置如图">
                    <Row style={{width: '100%', height: 400}}>
                        <Col span={24}>
                            <Map amapkey='4545b8cd5b830357e075e88eb7f336be' zoom={14} plugins={mapPlugins}
                                 center={{...mapCenter}}>
                                <Marker position={{...markerPosition}}/>
                            </Map>
                        </Col>
                    </Row>
                </Form.Item>
                <Row>
                    <Form.Item wrapperCol={{span: 12, offset: 6}}>
                        <Button type="primary" htmlType="submit" loading={loading}>保存
                        </Button>
                    </Form.Item>
                </Row>
            </Form>
            <Modal visible={previewVisible} footer={null} onCancel={handleCancel}>
                <img alt="预览图片" style={{width: '100%'}} src={previewImage}/>
            </Modal>
        </div>

    )
}

export default React.memo(BaseInfo);